import bisect

from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from django_filters import exceptions
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from api.models import Record
from api.serializers import RecordSerializer

from rest_framework.filters import BaseFilterBackend, SearchFilter, OrderingFilter


class Agefilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        tfs = request.query_params.get('age')
        if tfs and ',' in tfs:
            start, stop = str(tfs).split(',')
            if start and stop:
                queryset = queryset.filter(age__gte=int(start),age__lte=int(stop))
            elif start:
                queryset = queryset.filter(age__gte=int(start))
            elif stop:
                queryset = queryset.filter(age__lte=int(stop))
        return queryset


class Incomefilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        tfs = request.query_params.get('income')
        if tfs and ',' in tfs:
            start, stop = str(tfs).split(',')
            if start and stop:
                queryset = queryset.filter(income_monthly__gte=int(start),income_monthly__lte=int(stop))
            elif start:
                queryset = queryset.filter(income_monthly__gt=int(start))
            elif stop:
                queryset = queryset.filter(income_monthly__lt=int(stop))
        return queryset

class RecordDRFView(ModelViewSet):
    queryset = Record.objects.all()  # 数据集
    serializer_class = RecordSerializer  # 序列号器
    #search_fields = ('city',)  # 支持模糊搜索
    filterset_fields = ('city','degree')  # 指定过滤的字段
    #ordering_fields = ("income_monthly", 'city',)  # 排序字段
    filter_backends = [Agefilter,DjangoFilterBackend]

    @action(methods=['post'], detail=False)
    def evaluation(self, request):
        income = int(request.data.get('income'))
        age = request.data.get('age')
        city = request.data.get('city')
        begin_age = int(age)-1
        end_age =int(age)+1
        income_list= list(self.queryset.filter(city=city, age__gte=begin_age,age__lte=end_age).order_by('income_monthly').values("income_monthly"))
        if len(income_list)>0 :
            income_values=[obj['income_monthly'] for obj in income_list]
            income_values =list(set(income_values))
            try:
                position = income_values.index(income)
                ordered = len(income_values)-position
                print(f"数字 {income} 在列表中排行位置是：{ordered}")
                result = f'您的薪资在{city},年龄{begin_age}-{end_age}阶段排行第{ordered} '
            except ValueError:
                insert_index = bisect.bisect_left(income_values, income)
                income_values.insert(insert_index, income)
                ordered = len(income_values) - insert_index
                result = f'您的薪资在{city},年龄{begin_age}-{end_age}阶段排行第{ordered} '
                print(f"数字 {income} 在列表中排行位置是：{ordered}")
        else:
            result = f'您的薪资在{city},年龄{begin_age}-{end_age}阶段临时排行第1 '
            print(f"前无古人，后无来者")
        return Response(data=result, status=status.HTTP_200_OK)
